//
//  AddressEditCtr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/10/31.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation

//
//  NickNameEditCtr.swift
//  QCTasks
//
//  Created by zhu xietong on 2017/10/27.
//  Copyright © 2017年 zhuxietong. All rights reserved.
//

import Foundation
import UIKit
import soapp
import Eelay
//import TPKeyboardAvoiding

public enum AddressEditType {
    case add(NSMutableDictionary?)
    case edit(NSMutableDictionary)
    public var name:String{
        get{
            switch self {
            case .edit(_):
                return "修改收货地址".loc
            default:
                return "添加收货地址".loc
            }
        }
    }
    public var url:String{
        get{
            switch self {
            case .add:
                return _SURL.收货地址添加_修改.url
            default:
                return _SURL.收货地址添加_修改.url
            }
        }
    }
}

open class AddressEditCtr: ListController {
    public static var mobileField:JoTableCell.Type = SimpleTextCell.self
    
    public static var isGlobal = Goods.supportGlobal
    
    var editType:AddressEditType = .add(nil){
        didSet{
            switch editType {
            case .edit(let obj):
                self.mo.model = obj
            default:
                break
            }
        }
    }
    
    public var successAction:(AddressEditType,NSMutableDictionary)->Void = {_,_ in}
    
    open var sections:TP.section{
        get{
            var region = [mo.model["province",""],mo.model["city",""],mo.model["area",""]].joined(separator: "|").escapeHeadTailSpace()
            
            var globel_region = mo.model["description",""]
            if globel_region.len < 1{
                let region_json = Place.addressIDs(with: region).json_value
                globel_region = region_json
            }
//            print("+++_____S|",globel_region)
            
            var sec1:[[String:Any]] = [
                [
                    "title":"姓名".loc,
                    "cellID":"username",
                    FK.fields:[
                        [
                            FK.placeholder:"请输入收货人姓名".loc,
                            FK.value:mo.model["realname",""],
                            FK.field:StrField(id: "realname", defaultV: nil, need: true, hiden: false, rule:
                                JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请输入收货人姓名".loc, err_msg: "检查姓名".loc))
                        ]
                    ],
                ],
                [
                    "title":"手机".loc,
                    "cellID":"mobile",
                    FK.fields:[
                        [
                            FK.placeholder:"请输入手机号".loc,
                            FK.value:mo.model["mobile",""],
                            FK.field:StrField(id: "mobile", defaultV: nil, need: true, hiden: false, rule:
                                JoRule(reg: EeLogin.globalPhone, nil_msg: "请输入收货人手机号".loc, err_msg: "检查收货人手机号".loc))
                        ]
                    ],
                ],
                [
                    "title":"地区".loc,
                    "cellID":"area",
                    FK.fields:[
                        [
                            FK.placeholder:"选择地区".loc,
                            FK.value:globel_region,
                            FK.field:StrField(id: "place", defaultV: nil, need: true, hiden: false, rule:
                                JoRule(reg: "^[\\s\\S]{1,100000}$", nil_msg: "检查地区".loc, err_msg: "请检查地区".loc))
                        ]
                    ],
                ],
            ]
            if (Goods.supportGlobal){
                sec1.append([
                    "title":"邮编".loc,
                    "cellID":"zipcode",
                    FK.fields:[
                        [
                            FK.placeholder:"请输入邮编".loc,
                            FK.value:mo.model["zipcode",""],
                            FK.field:StrField(id: "zipcode", defaultV: nil, need: true, hiden: false, rule:
                                JoRule(reg: "^\\d{1,12}", nil_msg: "请输入邮编".loc, err_msg: "检查邮编".loc))
                        ]
                    ],
                ])
            }
            
            let sec = [
                [
                    ["id":"blank"]
                ],
                sec1,
                [
                    [
                        "title":"详细地址".loc,
                        "cellID":"address",
                        FK.fields:[
                            [
                                FK.placeholder:"详细地址".loc,
                                FK.value:mo.model["address",""],
                                FK.field:StrField(id: "address", defaultV: nil, need: true, hiden: false, rule:
                                    JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "请检查详细地址".loc, err_msg: "请检查详细地址".loc))
                            ]
                        ],
                    ],
//                    ["id":"submit"]
                ]
            ]
            return sec
        }
    }
    
    open var selector:TP.selector{
        get {
            return [
                    "id<blank>":BlankLine<line.px10>.self,
                    "<default>":SimpleTextCell.self,
            //        "cellID<area>":FAddressCell.self,
                    "cellID<mobile>":AddressEditCtr.mobileField,
                    "cellID<area>":FGlobalAddressCell.self,
                    "cellID<address>":TextAreaCell<line.px72>.self,
            //        "id<submit>":[SubmitCell.self],
                ]
        }
    }

    open override func viewDidLoad() {
        tableView = TPKeyboardAvoidingTableView(frame: .zero, style: .plain)
        super.viewDidLoad()
        tableView.buildDynamicHeight(height: 60)
        tableView.load(sections: sections, selector: selector)
        tableView.backgroundColor = UIColor.table_bg_color
        tableView.separatorStyle = .none
        tableView.tintColor = ___shop.tint
        title = self.editType.name
        FieldCell.name_width = 50
        FieldCell.padding_left = 21
        FieldCell.padding_right = 21
        
        

        
        // Do any additional setup after loading the view.
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定".loc, style: .plain, target: self, action: #selector(submitAction))

        self.navigationItem.rightBarButtonItem?.tintColor = UIColor.main_color
    }
    
    
//    override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
//        if actionID == "submit"
//        {
//            submitAction()
//        }
//    }
    
    
//    override func touch(cell: JoTableCell, actionID: String, model: NSMutableDictionary) {
//        if actionID == "submit"
//        {
//            submitAction()
//        }
//
//    }
    
    public lazy var hud:HUD = {
        return HUD(at: self.view)
    }()
    
    public func pawRegion()->([String:Any],Bool,String){
        let info = JoPaw.paw(tableView: tableView)
        if info.validate
        {
            if let region =  (info.values["place"] as? String)?.JsonDictionary{
                var vs = info.values
                vs.removeValue(forKey: "place")
                vs["province"] = region["province.name",""]
                vs["city"] = region["city.name",""]
                vs["area"] = region["area.name",""]
                vs["zipcode"] = region["area.zipcode",""]
                switch self.editType{
                case .edit(let obj):
                        vs["id"] = obj["id",""]
                default:
                        break
                }
                return (vs,true,"OK")
                
            }else if let region = (info.values["place"] as? String)?.JsonArray{
                var vs = info.values
                let place = vs.mutable_dictionary["place",""]
                vs.removeValue(forKey: "place")
                vs["description"] = place
                switch self.editType{
                case .edit(let obj):
                    vs["id"] = obj["id",""]
                    default:
                        break
                }
                return (vs,true,"OK")
            }else{
                return ([:],false,"地区数据无效".loc)
            }
        }else{
            return ([:],false,"")
        }
    }
    
    @objc open func submitAction() {
        
        
        let info = pawRegion()
        if info.1
        {
            
            
            
//            guard let region = (info.values["place"] as? String)?.JsonDictionary else{
//                "地区数据无效".loc.alert()
//                return
//            }
//            var vs = info.values
//            vs.removeValue(forKey: "place")
//            vs["province"] = region["province.name",""]
//            vs["city"] = region["city.name",""]
//            vs["area"] = region["area.name",""]
//            vs["zipcode"] = region["area.zipcode",""]
//            switch self.editType{
//            case .edit(let obj):
//                vs["id"] = obj["id",""]
//            default:
//                break
//            }

            var vs = info.0

            let editTP = self.editType

            
            weak var wself = self
            hud.show().mode(.indeterminate)

            
            JoTask().post.url(self.editType.url).params(vs).log.log_response().json_handle { (status, msg, obj, resp) in
                wself?.hud.hide(animated: true)
                if status.isSuccess{
                    switch editTP{
                    case .edit(_):
                        wself?.successAction(editTP, vs.mutable_dictionary)
                    case .add(_):
                        if let idObj = obj as? NSMutableDictionary
                        {
        
                            vs["id"] = idObj["id",""]
                            let address = vs.mutable_dictionary
                            wself?.successAction(.add(address), address)
                        }
                    }
                    wself?.navigationController?.popViewController(animated: true)
                    "保存成功".loc.alert()
                    return
                }
                msg.alert()
            }.run()
        }else{
            if (info.2).len > 1{
                info.2.loc.alert()
            }
        }
    }
    
    open override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}
extension AddressEditCtr{

    class SubmitCell:JoTableCell{
        let bt = UIButton()
        override func addLayoutRules() {
            contentView.eelay = [
                [bt,[ee.T.B.X,[80,-30,0]],"36",180]
            ]
            bt.ui.buttonColor(hex: UIColor.main_hex).font(size: 15).ntitle(title: "保存").ncolor(hex: "#fff").set(radius: 4, width: nil, color: nil)
            self.backgroundColor = .clear
            contentView.backgroundColor = .clear
            
            //            bt.contentEdgeInsets = [6,14]
            bt.addTarget(self, action: #selector(submit), for: .touchUpInside)
        }
        
        @objc func submit() {
            active(ID: "submit")
        }
        
    }
    
}




